//
//  HSOrderViewController.m
//  hsdyOrderSystem
//
//  Created by 赖国锋 on 2017/11/8.
//  Copyright © 2017年 赖国锋. All rights reserved.
//
#import "HSOrderViewController.h"
#import "HSOrderCell.h"
#import "HSOrderMoreCell.h"
#import "HSOrderModel.h"
#import <UITableView+FDTemplateLayoutCell.h>
#import "HSOrderDetailViewController.h"
#import "HSOrderDetailModel.h"
#import "HSFenliangModel.h"
#import "HSGuigeModel.h"
#import "WZLBadgeImport.h"
/*
 01-推送改环境
 02-推送声音
 03-启动页
 
 */

static NSString * const reuseIdentifier = @"orderCell";
static NSString * const moreReuseIdentifier =@"moreCell";

@interface HSOrderViewController ()

@property(strong,nonatomic)UIButton * appointmentBtn;//预约订单
@property(strong,nonatomic)UIButton * willUpBtn;//待上菜
@property(strong,nonatomic)UIButton * readyUpBtn;//已上菜

@property(strong,nonatomic)UIView *tipView;
@property(assign,nonatomic)BOOL isHaveReadyUpBtn;//是否有已上菜按钮

@property(assign,nonatomic)NSInteger status;//状态

@property(assign,nonatomic)NSInteger appointmentNum;//预约单未读
@property(assign,nonatomic)NSInteger normalNum;//正常单未读
@property(assign,nonatomic)NSInteger allNum;//所有单未读
@end

@implementation HSOrderViewController
-(void)dealloc{
    lNOTIF_REMV();
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] init];
    [self postNormalUnRead];
    [self postReservationUnRead];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isHaveReadyUpBtn = YES;
    self.status = 2;
    [self startPullDownRefreshing];
    lNOTIF_ADD(sureOrderSuccessNoti, sureOrderSuccess);
    lNOTIF_ADD(receivePushMessageSuccessNoti, receivePushMessageSuccess);//接受到推送消息成功
}

-(void)receivePushMessageSuccess{
    self.requestCurrentPage = 1;
     [self loadDataSource];
}

-(void)sureOrderSuccess{
    [self loadDataSource];
}

//正常订单未读
-(void)postNormalUnRead{
    [self showLoadingWithClear:YES];
    WEAKSELF
    [XFPostRequest postGetNormalUnReadByShopId:[BookShareUserInforDefault readUserUid] success:^(id responseObject) {
        LGFLog(@"===%@",responseObject);
        [weakSelf hideLoading];
        if (responseObject == nil)  return ;
        if ([responseObject[@"status"] intValue] == 200){
            NSInteger unreadNomal = [[responseObject safeJsonObjectForKey:@"content"] integerValue];
            [_willUpBtn showBadgeWithStyle:WBadgeStyleNumber value:unreadNomal animationType:WBadgeAnimTypeScale];
        }
    } failure:^(NSError *error) {
        [weakSelf hideLoading];
        [SOAutoHideMessageView showMessage:LNETWORKERROR inView:nil];
    }];
}

//预约订单未读
-(void)postReservationUnRead{
    [self showLoadingWithClear:YES];
    WEAKSELF
    [XFPostRequest postGetReservationUnReadByShopId:[BookShareUserInforDefault readUserUid] success:^(id responseObject) {
        LGFLog(@"===%@",responseObject);
        [weakSelf hideLoading];
        if (responseObject == nil)  return ;
        if ([responseObject[@"status"] intValue] == 200){
             NSInteger unreadNomal = [[responseObject safeJsonObjectForKey:@"content"] integerValue];
            [_appointmentBtn showBadgeWithStyle:WBadgeStyleNumber value:unreadNomal animationType:WBadgeAnimTypeScale];
        }
    } failure:^(NSError *error) {
        [weakSelf hideLoading];
        [SOAutoHideMessageView showMessage:LNETWORKERROR inView:nil];
    }];
}

-(void)exchangeView{
    UIView* superView = [[UIView alloc]init];
    superView.backgroundColor = [UIColor whiteColor];
    superView.frame = CGRectMake(0,0,SCREEN_WIDTH,44);
    [self.view addSubview:superView];
    
    _appointmentBtn = [UIButton buttomWithTitle:@"预约单" titleNormalColor:lColorBlack titleSelectColor:LCOLOROFNAV backgroundColor:XFUIColorFromRGB(0xFFFFFF) font:14  normalBackgroundImage:nil selectBackgroundImage:@""];
    _appointmentBtn.tag = 1001;
    
    
    [superView addSubview:_appointmentBtn];
    [_appointmentBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    _appointmentBtn.selected = YES;
    
    [_appointmentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(superView);
        make.width.mas_equalTo(SCREEN_WIDTH/3);
    }];
    
    _willUpBtn =[UIButton buttomWithTitle:@"待上菜" titleNormalColor:lColorBlack titleSelectColor:LCOLOROFNAV backgroundColor:XFUIColorFromRGB(0xFFFFFF) font:14 normalBackgroundImage:nil selectBackgroundImage:@""];
    [_willUpBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    _willUpBtn.tag = 1002;
    [superView addSubview:_willUpBtn];
    
    [_willUpBtn setBackgroundColor:[UIColor clearColor]];
    [_willUpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_appointmentBtn.mas_right);
        make.top.bottom.equalTo(superView);
        make.width.mas_equalTo(SCREEN_WIDTH/3);
    }];
    
    _readyUpBtn =[UIButton buttomWithTitle:@"已上菜" titleNormalColor:lColorBlack titleSelectColor:LCOLOROFNAV backgroundColor:XFUIColorFromRGB(0xFFFFFF) font:14 normalBackgroundImage:nil selectBackgroundImage:@""];
    [_readyUpBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    _readyUpBtn.tag = 1003;
    [superView addSubview:_readyUpBtn];
    [_readyUpBtn setBackgroundColor:[UIColor clearColor]];
    [_readyUpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(superView);
        make.width.mas_equalTo(SCREEN_WIDTH/3);
    }];
    
    self.tipView = [[UIView alloc] init];
    self.tipView.backgroundColor = LCOLOROFNAV;
    [superView addSubview:self.tipView];
    [self.tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.equalTo(superView);
        make.width.mas_equalTo(SCREEN_WIDTH/3);
        make.height.mas_equalTo(2);
    }];
}


- (void)buttonClick:(UIButton *)sender{
    for (int i = 1001; i < 1004; i++) {
        UIButton * button = (UIButton *)[self.view viewWithTag:i];
        LGFLog(@" ==button= %@ --sender= %@",button,sender);
        if (button == sender) {
            //刷新下标
//            [self postNormalUnRead];
//            [self postReservationUnRead];
            button.selected = YES;
            self.requestCurrentPage = 1;
            [self.dataSource removeAllObjects];
//            1是正常用餐，2是预约的，3是历史
            if (sender.tag == 1001) {//预约单
                
                self.isHaveReadyUpBtn = YES;
                self.status = 2;
                [UIView animateWithDuration:0.2 animations:^{
                    self.tipView.x = 0;
                }];
                [self ClickWaringBtn];
                
            }else if (sender.tag == 1002){//待上菜
                self.isHaveReadyUpBtn = YES;
                self.status = 1;
                [UIView animateWithDuration:0.2 animations:^{
                    self.tipView.x =SCREEN_WIDTH*1.0/3;
                }];
                [self ClickNotificationBtn];
            }else if (sender.tag == 1003){//已上菜
                self.isHaveReadyUpBtn = NO;
                 self.status = 3;
                [UIView animateWithDuration:0.2 animations:^{
                    self.tipView.x = SCREEN_WIDTH*2.0/3;
                }];
                [self ClickNotificationBtn];
            }
        } else{
            button.selected = NO;
        }
    }
}

//完成订单
-(void)ClickWaringBtn{
    [self loadDataSource];
}

//历史订单
-(void)ClickNotificationBtn{
    [self loadDataSource];
}

-(void)initViews{
    [self initTableView];
//    [self headerRereshing];
    [self exchangeView];
}

- (void)initTableView{
    [self initTableViewWithStyle:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:[NSString stringWithFormat:@"%@",[HSOrderCell class]] bundle:nil ] forCellReuseIdentifier:reuseIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:[NSString stringWithFormat:@"%@",[HSOrderMoreCell class]] bundle:nil ] forCellReuseIdentifier:moreReuseIdentifier];
    self.tableView.backgroundColor = XFUIColorFromRGB(0xf0f2f5);
    [self.view addSubview:self.tableView];
    WEAKSELF
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.top.equalTo(weakSelf.view).offset(44);
        make.bottom.equalTo(weakSelf.view).offset(-50);
    }];
}

#pragma mark - Data Source
- (void)loadDefaultDataSource{
    [super loadDefaultDataSource];
    self.blankHintImage = [UIImage imageNamed:@""];
    self.blankHintString=@"暂无订单数据";
}

-(void)loadDataSource{
    [self showLoadingWithClear:YES];
//    [MBProgressHUD showMessage:nil dissmissTime:0];
    WEAKSELF
    //1是正常用餐，2是预约的，3是历史，这里默认展示用户已支付的
    [XFPostRequest postaddWaiterShopId:[BookShareUserInforDefault readUserUid] status:self.status page:[NSString stringWithFormat:@"%zd",self.requestCurrentPage] success:^(id responseObject) {
        LGFLog(@"===%@",responseObject);
        
        if ([responseObject[@"status"] intValue] == 200){
            //获取页数
            NSInteger page =  [[responseObject safeJsonObjectForKey:@"msg"] integerValue];
            weakSelf.isPageEnd = weakSelf.requestCurrentPage == page;
            
            [weakSelf postNormalUnRead];//正常消息
            [weakSelf postReservationUnRead];//预约消息
            [weakSelf addToDataSource:[HSOrderModel orderWithArray:responseObject[@"content"]]];
            
            if (self.dataSource.count == 0) {
                [weakSelf endPullDownRefreshing];
                [weakSelf setIsPageEnd:YES];
            }
        }
        else {
            [weakSelf hideLoading];
            if (![[HSOrderModel mj_objectArrayWithKeyValuesArray:responseObject[@"content"]] isKindOfClass:[NSArray class]]) {
                [weakSelf.dataSource removeAllObjects];
                [weakSelf reloadDataWithBlank];
            }
            
            [weakSelf endPullDownRefreshing];
            [weakSelf setIsPageEnd:YES];
        }
        
//        [MBProgressHUD hideHUD];
        [weakSelf.tableView reloadData];
        [weakSelf hideLoading];
    } failure:^(NSError *error) {
        [weakSelf setIsPageEnd:YES];
        [weakSelf endPullDownRefreshing];
        [weakSelf reloadDataWithBlank];
        [weakSelf hideLoading];
        [MBProgressHUD showError:LNETWORKERROR];
    }];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    LGFLog(@"self.dataSource.count = %zd",self.dataSource.count);
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    HSOrderModel * model = self.dataSource[indexPath.row];
    model.isHaveReadyUpBtn = self.isHaveReadyUpBtn;
    if (self.status == 2) {
        model.isShowComingtime = YES;
    }else{
         model.isShowComingtime = NO;
    }
    if (model.foodsList.count > 1) {//多种菜品时
        HSOrderMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:moreReuseIdentifier];
        cell.model = model;
        cell.selectionStyle = 0;
        cell.DetailBtnBlock = ^(NSInteger tag){
            HSOrderDetailViewController *orderDetailVC = [HSOrderDetailViewController new];
            orderDetailVC.model = model;
            [weakSelf.navigationController pushViewController:orderDetailVC animated:YES];
        };
        cell.CompleteBtnBlock = ^(NSInteger tag) {
            LGFLog(@"点击了已上菜 id= %@",model.outTradeNo);
             [weakSelf postUpDishesWithoutTradeNo:model.outTradeNo];
//            [weakSelf postSureOrderRequest:model.outTradeNo];
        };
        return cell;
    }else{
        HSOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        cell.DetailBtnBlock = ^(NSInteger tag){
            HSOrderDetailViewController *orderDetailVC = [HSOrderDetailViewController new];
            orderDetailVC.model = model;
            [weakSelf.navigationController pushViewController:orderDetailVC animated:YES];
        };
        cell.CompleteBtnBlock = ^(NSInteger tag) {
            [weakSelf postUpDishesWithoutTradeNo:model.outTradeNo];
        };
        cell.selectionStyle = 0;
        cell.model = model;
        return cell;
    }
}

-(void)postUpDishesWithoutTradeNo:(NSString *)outTradeNo{
    WEAKSELF
    [UIAlertController alertControllerShowInController:self Title:@"提示" message:@"是否确认已上菜？" checkBlock:^{
        LGFLog(@"点击了已上菜 id= %@",outTradeNo);
        [weakSelf postSureOrderRequest:outTradeNo];
    }];
}


#pragma mark - 已上菜
-(void)postSureOrderRequest:(NSString *)outTradeNo{
    [self showLoadingWithClear:YES];
    WEAKSELF
    [XFPostRequest postupdateSureOrderByShopId:[BookShareUserInforDefault readUserUid] outTradeNo:outTradeNo success:^(id responseObject) {
        [weakSelf hideLoading];
        if ([[responseObject safeJsonObjectForKey:@"status"] integerValue] ==200) {
            LGFLog(@"上菜成功");
            [weakSelf loadDataSource];
        }else{
            [SOAutoHideMessageView showMessage:[responseObject safeJsonObjectForKey:@"msg"] inView:weakSelf.view];
        }
    } failure:^(NSError *error) {
        [weakSelf hideLoading];
         [SOAutoHideMessageView showMessage:LNETWORKERROR inView:weakSelf.view];
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HSOrderModel * model = self.dataSource[indexPath.row];
    if (model.foodsList.count > 1) {//多种菜品时
        return [tableView fd_heightForCellWithIdentifier:moreReuseIdentifier configuration:^(HSOrderMoreCell *cell) {
            cell.model = model;
        }];
    }else{
        return [tableView fd_heightForCellWithIdentifier:reuseIdentifier configuration:^(HSOrderCell *cell) {
            HSOrderModel * model = self.dataSource[indexPath.row];
            cell.model = model;
        }];
    }
}

@end
